// 钉钉登录插件 JavaScript

// 切换钉钉插件启用状态
function toggleDingtalkStatus() {
    const checkbox = document.getElementById('dingtalk-enabled');
    const isEnabled = checkbox.checked;
    const form = document.getElementById('dingtalk-form');
    
    showDingtalkMessage(isEnabled ? '正在启用钉钉登录...' : '正在禁用钉钉登录...', 'info');
    
    // 切换表单禁用状态
    if (isEnabled) {
        form.classList.remove('disabled');
    } else {
        form.classList.add('disabled');
    }
    
    // 发送状态更新请求
    fetch('plugin/dingtalk/toggle-status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            enabled: isEnabled
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showDingtalkMessage(data.message || '状态更新成功', 'success');
        } else {
            showDingtalkMessage(data.message || '状态更新失败', 'error');
            // 恢复状态
            checkbox.checked = !isEnabled;
            if (!isEnabled) {
                form.classList.remove('disabled');
            } else {
                form.classList.add('disabled');
            }
        }
    })
    .catch(error => {
        showDingtalkMessage('状态更新失败：' + error.message, 'error');
        // 恢复状态
        checkbox.checked = !isEnabled;
        if (!isEnabled) {
            form.classList.remove('disabled');
        } else {
            form.classList.add('disabled');
        }
    });
}

// 测试钉钉连接
function testDingtalkConnection() {
    const form = document.getElementById('dingtalk-form');
    
    if (!validateDingtalkForm()) {
        return;
    }
    
    showDingtalkMessage('正在测试钉钉连接...', 'info');
    
    const formData = new FormData(form);
    
    fetch('plugin/dingtalk/test-connection.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showDingtalkMessage(data.message || '连接测试成功', 'success');
        } else {
            showDingtalkMessage(data.message || '连接测试失败', 'error');
        }
    })
    .catch(error => {
        showDingtalkMessage('连接测试失败：' + error.message, 'error');
    });
}

// 保存钉钉配置
function saveDingtalkConfig() {
    const form = document.getElementById('dingtalk-form');
    
    if (!validateDingtalkForm()) {
        return;
    }
    
    showDingtalkMessage('正在保存配置...', 'info');
    
    const formData = new FormData(form);
    
    fetch('plugin/dingtalk/save-config.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showDingtalkMessage(data.message || '配置保存成功', 'success');
        } else {
            showDingtalkMessage(data.message || '配置保存失败', 'error');
        }
    })
    .catch(error => {
        showDingtalkMessage('配置保存失败：' + error.message, 'error');
    });
}

// 验证表单
function validateDingtalkForm() {
    const appKey = document.getElementById('dingtalk-app-key').value.trim();
    const appSecret = document.getElementById('dingtalk-app-secret').value.trim();
    const corpId = document.getElementById('dingtalk-corp-id').value.trim();
    const redirectUri = document.getElementById('dingtalk-redirect-uri').value.trim();
    
    if (!appKey) {
        showDingtalkMessage('请输入 AppKey', 'error');
        return false;
    }
    
    if (!appSecret) {
        showDingtalkMessage('请输入 AppSecret', 'error');
        return false;
    }
    
    if (!corpId) {
        showDingtalkMessage('请输入企业 CorpId', 'error');
        return false;
    }
    
    if (!redirectUri) {
        showDingtalkMessage('请输入回调地址', 'error');
        return false;
    }
    
    // 验证 URL 格式
    try {
        new URL(redirectUri);
    } catch (e) {
        showDingtalkMessage('回调地址格式不正确', 'error');
        return false;
    }
    
    return true;
}

// 显示消息
function showDingtalkMessage(message, type = 'info') {
    const messageElement = document.getElementById('dingtalk-message');
    messageElement.textContent = message;
    messageElement.className = 'dingtalk-message show ' + type;
    
    // 3秒后自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            messageElement.classList.remove('show');
        }, 3000);
    }
}

// 钉钉登录 - 获取登录二维码
function getDingtalkQRCode() {
    showDingtalkMessage('正在获取钉钉登录二维码...', 'info');
    
    fetch('plugin/dingtalk/get-qrcode.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示二维码
            displayQRCode(data.qrcode_url);
        } else {
            showDingtalkMessage(data.message || '获取二维码失败', 'error');
        }
    })
    .catch(error => {
        showDingtalkMessage('获取二维码失败：' + error.message, 'error');
    });
}

// 显示二维码（示例函数）
function displayQRCode(url) {
    // 这里可以实现二维码显示逻辑
    console.log('QR Code URL:', url);
}

// 暴露到全局
window.toggleDingtalkStatus = toggleDingtalkStatus;
window.testDingtalkConnection = testDingtalkConnection;
window.saveDingtalkConfig = saveDingtalkConfig;
window.getDingtalkQRCode = getDingtalkQRCode;
